import React, { useState, forwardRef, useImperativeHandle } from 'react';
import { MenuOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { DndContext } from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import {
    arrayMove,
    SortableContext,
    useSortable,
    verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Modal, Table, message, Tooltip } from 'antd';
import { apiUpdateLibraryPriority } from '@/request/storageManager/store.js'
const columns = [
    {
        key: 'sort',
    },
    {
        title: '拥有仓库',
        dataIndex: 'name',
    }
];
const Row = ({ children, ...props }) => {
    const {
        attributes,
        listeners,
        setNodeRef,
        setActivatorNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({
        id: props['data-row-key'],
    });
    const style = {
        ...props.style,
        transform: CSS.Transform.toString(
            transform && {
                ...transform,
                scaleY: 1,
            },
        ),
        transition,
        ...(isDragging
            ? {
                position: 'relative',
                zIndex: 9999,
            }
            : {}),
    };
    return (
        <tr {...props} ref={setNodeRef} style={style} {...attributes}>
            {React.Children.map(children, (child) => {
                if (child.key === 'sort') {
                    return React.cloneElement(child, {
                        children: (
                            <MenuOutlined
                                ref={setActivatorNodeRef}
                                style={{
                                    touchAction: 'none',
                                    cursor: 'move',
                                }}
                                {...listeners}
                            />
                        ),
                    });
                }
                return child;
            })}
        </tr>
    );
};
const App = (props, ref) => {
    useImperativeHandle(ref, () => ({ // 暴露给父组件的方法
        open
    }))
    const [isModalVisible, setIsModalVisible] = useState(false)
    const [dataSource, setDataSource] = useState([]);
    const [storeId, setStoreId] = useState('')
    const onDragEnd = ({ active, over }) => {
        if (active.id !== over?.id) {
            setDataSource((previous) => {
                const activeIndex = previous.findIndex((i) => i.key === active.id);
                const overIndex = previous.findIndex((i) => i.key === over?.id);
                return arrayMove(previous, activeIndex, overIndex);
            });
        }
    };
    const open = (dataSource, storeId) => {
        setStoreId(storeId)
        setDataSource(dataSource)
        setIsModalVisible(true)
    }
    const handleOk = () => {
        apiUpdateLibraryPriority({
            libraryId: dataSource.map(item => item.id),
            storeId: storeId
        }).then(res => {
            if (res.code === 0) {
                message.success(res.codeMessage)
                handleCancel()
            }
        })
    }
    const handleCancel = () => {
        setIsModalVisible(false)
    }
    return (
        <div>
            <Modal title={
                <Tooltip title={`新订单将基于收货地址所在的区域，根据地区匹配策 略去适配仓库。
                若地区匹配策略匹配失败，则根据仓库优先级来匹配
                仓库，若单一仓库无法履约，则会进行拆单。`}>
                    仓库优先级<QuestionCircleOutlined />
                </Tooltip>
            } visible={isModalVisible} width="500px"
                onOk={handleOk} onCancel={handleCancel}
            >
                <DndContext modifiers={[restrictToVerticalAxis]} onDragEnd={onDragEnd}>
                    <SortableContext
                        // rowKey array
                        items={dataSource.map((i) => i.key)}
                        strategy={verticalListSortingStrategy}
                    >
                        <Table
                            components={{
                                body: {
                                    row: Row,
                                },
                            }}
                            rowKey="key"
                            columns={columns}
                            dataSource={dataSource}
                            pagination={false}
                        />
                    </SortableContext>
                </DndContext>


            </Modal>
        </div>

    );
};

export default forwardRef(App);